﻿using System;
using System.Collections.Generic;
using System.Web;
using PdfSharp;
using PdfSharp.Drawing;
using PdfSharp.Pdf;
using System.IO;
using PdfSharp.Pdf.IO;

/// <summary>
///PDFGenetor 的摘要说明
/// </summary>
public class PDFGenetor
{
	public PDFGenetor()
	{
		//
		//TODO: 在此处添加构造函数逻辑
		//
	}
    /// <summary>
    /// combine all pdf files under the input directory 
    /// </summary>
    /// <param name="inputPath">input directory path</param>
    /// <param name="outputfn">output pdf file name(.full pysics path.)</param>
    public static void CombinePdf(string inputPath, string outputfn)
    {
        List<string> dir = new List<string>();
        foreach (string fi in Directory.GetFiles(inputPath))
        {
            dir.Add(fi);
        }
        
        //对得到的文件名称进行排序
        dir.Sort(UtilsList.CompareDinosByLength);

        // Create the output document 
        PdfDocument outputDocument = new PdfDocument();
        foreach (string f in dir)
        {
            PdfDocument inputdoc = PdfReader.Open(f, PdfDocumentOpenMode.Import);
            for (int i = 0; i < inputdoc.PageCount; i++)
            {
                PdfPage page = inputdoc.Pages[i];
                outputDocument.AddPage(page);
            }

        }

        outputDocument.Save(outputfn);
    }
    /// <summary>
    /// convert some image files to a pdf file document .
    /// </summary>
    /// <param name="pdffilename"></param>
    /// <param name="imgfiles"></param>
    private static void ImgtoPdf(string pdffilename, List<string> imgfiles)
    {
        PdfDocument doc = new PdfDocument();
        doc.Info.CreationDate = DateTime.Now;
        doc.Info.Creator = "";
        for (int i = 0; i < imgfiles.Count; i++)
        {
            doc.Pages.Add(new PdfPage());
            XGraphics xgr = XGraphics.FromPdfPage(doc.Pages[i]);
            XImage img = XImage.FromFile(imgfiles[i]);
            xgr.DrawImage(img, 0, 0);
            img.Dispose();
            //xgr.Dispose();
        }
        
        doc.Save(pdffilename);
        doc.Close();
    }

    /// <summary>
    /// 
    /// </summary>
    /// <param name="pdffilename"></param>
    /// <param name="imgpath">image files path</param>
    public static void ImgtoPdf(string pdffilename, string imgpath)
    {
        List<string> dir = new List<string>();
        foreach (string fi in Directory.GetFiles(imgpath))
        {
            dir.Add(fi);
        }

        //对得到的文件名称进行排序
        dir.Sort(UtilsList.CompareDinosByLength);

        ImgtoPdf(pdffilename,dir);
    }

}